package com.ttt.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttt.service.UserLoginService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/*
*controller层，处理前端的请求，调用service接口
*
*
 */

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        resp.setContentType("text/html;charset=utf-8");

        System.out.println("id=" + id + "password=" + password);

        //实例化对象
        UserLoginService userLoginService = new UserLoginService();

        //查找用户，判断是否存在
        boolean byUser = false;
        try {
            byUser = userLoginService.findByUser(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //从数据库上获取密码，进行密码比对
        String inDataPassword = null;
        try {
            inDataPassword = userLoginService.findByUserPassword(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
//        boolean byUser = true;
        // 构建前端需要的JSON格式
        Map<String, Object> responseData = new HashMap<>();

        responseData.put("flag",byUser);
        responseData.put("inDatePassword",inDataPassword);
        System.out.println("Controller inDataPassword  = " + inDataPassword);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseData);
        // 设置响应头
        resp.setContentType("application/json");
        // 输出响应
        PrintWriter out = resp.getWriter();
        out.print(json);
        System.out.println(json);

        //到数据库里面查询是否有此账号
//        resp.sendRedirect("html/personalcenter.html");
    }
}
